import QRCode, { QRErrorCorrectLevel } from "./qrcode";

export default function ($) {
    if ($.fn.qrcode) return;

    $.fn.qrcode = function (options) {
        // if options is string, 
        if (typeof options === 'string') {
            options = { text: options };
        }

        // set default values
        // typeNumber < 1 for automatic calculation
        options = $.extend({}, {
            render: "canvas",
            width: 256,
            height: 256,
            typeNumber: -1,
            correctLevel: QRErrorCorrectLevel.H,
            background: "#ffffff",
            foreground: "#000000"
        }, options);

        var createCanvas = function () {
            // create the qrcode itself
            var qrcode = new QRCode(options.typeNumber, options.correctLevel);
            qrcode.addData(options.text);
            qrcode.make();

            // create canvas element
            var canvas = document.createElement('canvas');
            canvas.width = options.width;
            canvas.height = options.height;
            var ctx = canvas.getContext('2d');

            // compute tileW/tileH based on options.width/options.height
            var tileW = options.width / qrcode.getModuleCount();
            var tileH = options.height / qrcode.getModuleCount();

            // draw in the canvas
            for (var row = 0; row < qrcode.getModuleCount(); row++) {
                for (var col = 0; col < qrcode.getModuleCount(); col++) {
                    ctx.fillStyle = qrcode.isDark(row, col) ? options.foreground : options.background;
                    var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
                    var h = (Math.ceil((row + 1) * tileH) - Math.floor(row * tileH));
                    ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
                }
            }
            // return just built canvas
            return canvas;
        }

        // from Jon-Carlos Rivera (https://github.com/imbcmdth)
        var createTable = function () {
            // create the qrcode itself
            var qrcode = new QRCode(options.typeNumber, options.correctLevel);
            qrcode.addData(options.text);
            qrcode.make();

            // create table element
            var $table = $('<table></table>')
                .css("width", options.width + "px")
                .css("height", options.height + "px")
                .css("border", "0px")
                .css("border-collapse", "collapse")
                .css('background-color', options.background);

            // compute tileS percentage
            var tileW = options.width / qrcode.getModuleCount();
            var tileH = options.height / qrcode.getModuleCount();

            // draw in the table
            for (var row = 0; row < qrcode.getModuleCount(); row++) {
                var $row = $('<tr></tr>').css('height', tileH + "px").appendTo($table);

                for (var col = 0; col < qrcode.getModuleCount(); col++) {
                    $('<td></td>')
                        .css('width', tileW + "px")
                        .css('background-color', qrcode.isDark(row, col) ? options.foreground : options.background)
                        .appendTo($row);
                }
            }
            // return just built canvas
            return $table;
        }


        return this.each(function () {
            var element = options.render == "canvas" ? createCanvas() : createTable();
            $(element).appendTo(this);
        });
    };

    // 基于jquery.qrcode.min.js的二维码生成插件
    /** 用法：
        $('#ylmqrcode').ylmqrcode({
            text:"https://www.mao-app.com/wxchat/Index/index?sing=qApZBM6GGPBejOYs+VGvKg==",
            logo:"https://ylm.mao-app.com/img/cat.png"
        });
    **/
    $.fn.ylmqrcode = function (param) {
        var defaults = {
            width: 800, // 二维码宽度
            height: 800, // 二维码高度
            padding: 48, // 二维码内边距
            text: '', // 待生成二维码的文本内容
            bgColor: '#fff', // 二维码背景色
            fgColor: '#000', // 二维码前景色
            correctLevel: 1, // 二维码容错参数0/1/2/3
            logo: '', // 二维码中间的logo的src，false表示不要logo
            logoWidth: 152, // logo的宽度
            logoHeight: 152, // logo的高度
            logoPadding: 16, // logo的内边距
            logoBgColor: '#fff' // logo背景色
        };
        param = $.extend({}, defaults, param);

        var $box = this,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d');
        canvas.width = param.width,
            canvas.height = param.height;

        // 绘制二维码背景色
        ctx.fillStyle = param.bgColor;
        ctx.fillRect(0, 0, param.width, param.height);

        // 绘制二维码
        var erweima = $('<div></div>').qrcode({
            width: param.width - param.padding * 2,
            height: param.height - param.padding * 2,
            text: param.text,
            correctLevel: param.correctLevel
        }).children()[0];
        ctx.drawImage(erweima, param.padding, param.padding);

        if (param.logo) {
            var img = new Image();
            img.src = param.logo;
            img.onload = function () {
                // 绘制logo背景色
                ctx.fillStyle = param.logoBgColor;
                var lw = param.logoWidth,
                    lh = param.logoHeight,
                    startX = (param.width - lw) / 2,
                    startY = (param.height - lh) / 2;
                ctx.fillRect(startX, startY, lw, lh);

                // 绘制logo
                var logoMaxW = lw - param.logoPadding * 2,
                    logoMaxH = lh - param.logoPadding * 2,
                    wh = this.width / this.height;
                if (logoMaxW / logoMaxH > wh) {
                    var w = logoMaxH * wh,
                        h = logoMaxH;
                } else {
                    var w = logoMaxW,
                        h = logoMaxW / wh;
                }
                var x = (param.width - w) / 2;
                var y = (param.height - h) / 2;
                ctx.drawImage(this, x, y, w, h);
                return $box.append(canvas);
            };
            img.onerror = function () {
                alert('logo资源加载失败，点确认生成没有logo的二维码');
                return $box.append(canvas);
            }
        } else {
            return $box.append(canvas);
        }
    };
}
